package com.template.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.template.properties.AliOssProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
@Component
public class AliOssUtil {

    @Autowired
    private AliOssProperties aliOSSProperties;

    public static final String ALI_DOMAIN="https://web-tlias-lkc.oss-cn-beijing.aliyuncs.com/";//外网访问，bucket域名


    public String upload(MultipartFile file) throws IOException {

        String ENDPOINT=aliOSSProperties.getEndpoint();
        String ACCESS_KEY_ID=aliOSSProperties.getAccessKeyId();
        String ACCESS_KEY_SECRET=aliOSSProperties.getAccessKeySecret();
        String BUCKET_NAME=aliOSSProperties.getBucketName();

        //生成的文件名
        String originaFilename= file.getOriginalFilename();//原来的图片名
        String ext="."+ FilenameUtils.getExtension(originaFilename);
        String uuid= UUID.randomUUID().toString().replace("-","");
        String timeId= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"));
//        String fileName=uuid+ext;
        String fileName=timeId+"-"+uuid+ext;

        //oss客户端对象
        OSS ossClient=new OSSClientBuilder().build(ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
        ossClient.putObject(
                BUCKET_NAME,
                fileName,
                file.getInputStream()
        );
        ossClient.shutdown();
        String filePath="https://" + BUCKET_NAME + "." + ENDPOINT + "/" + fileName;
        log.info("上传文件的oss地址{}",filePath);
        return filePath;
    }



    /**
     * 文件删除
     * 删除文件或目录。如果要删除目录，目录必须为空
     *
     * @param link 文件全链接
     */
    public String deleteFile(String link) {

        String ENDPOINT=aliOSSProperties.getEndpoint();//外网访问，地域节点
        String ACCESS_KEY_ID=aliOSSProperties.getAccessKeyId();
        String ACCESS_KEY_SECRET=aliOSSProperties.getAccessKeySecret();
        String BUCKET_NAME=aliOSSProperties.getBucketName();

        if (link == null || link.trim().isEmpty()) {
            return "链接为空！";
        }

        // 验证链接是否有效
        if (!link.startsWith("http://") && !link.startsWith("https://")) {
            return "无效的链接格式！";
        }

        // 处理链接，提取文件路径
        link=link.substring(link.indexOf("//")+2);
        link=link.substring(link.indexOf("/")+1);

        //创建oss客户端
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            // 删除文件
            ossClient.deleteObject(BUCKET_NAME, link);
            log.info("文件删除成功: {}", link);
            return "文件删除成功！";
        } catch (OSSException oe) {
            log.error("OSSException: 错误信息: {}, 错误代码: {}, 请求 ID: {}, 主机 ID: {}",
                    oe.getErrorMessage(), oe.getErrorCode(), oe.getRequestId(), oe.getHostId());
            return "文件删除失败: " + oe.getErrorMessage();
        } catch (ClientException ce) {
            log.error("ClientException: 错误信息: {}", ce.getMessage());
            return "文件删除失败: " + ce.getMessage();
        }
    }



}
